#ifndef MYMAPCANVAS_H
#define MYMAPCANVAS_H

#include "textqgsmapcanvasitem.h"

#include <qgsannotationlayer.h>
#include <qgsannotationpointtextitem.h>
#include <qgsmapcanvas.h>


class MyMapCanvas : public QgsMapCanvas
{
public:
    MyMapCanvas();

    void addTraceLine(QgsPointXY & point);
    void addTracePoint(QgsPointXY &point);
    QgsPointXY getLastPoint() const;
    void setLastPoint(QgsPointXY newLastPoint);

    void setAnnotationLayer(QgsAnnotationLayer *newAnnotationLayer);

private:
    QgsPointXY lastPoint;  // 最后一个轨迹点
    TextQgsMapCanvasItem* coordItem;
    QgsAnnotationLayer* annotationLayer = nullptr;
    // 创建文本标注
    QgsAnnotationPointTextItem* textItem = nullptr;
    int id = 1;
protected:
    void mousePressEvent(QMouseEvent *event) override {
        if (event->button() == Qt::LeftButton) {
            QgsPointXY point = getCoordinateTransform()->toMapCoordinates(event->pos());
            qDebug() << "Left button clicked at:" << point.x() << point.y();
            addTraceLine(point);
            addTracePoint(point);

            QString coordText = QString("X: %1, Y: %2").arg(event->pos().x()).arg(event->pos().y());

            textItem->setText(coordText);
            textItem->setPoint(point);

           // coordItem->setPos();
           // coordItem->setPosition(event->pos());
           // coordItem->setText(coordText);
            // Tip : 默认可见，不用刷新也可见
            //coordItem->setVisible(true);
            //coordItem->setZValue(100);
            //this->refresh();

            QgsMapCanvas::mousePressEvent(event);
        }

    }

    // void mouseMoveEvent(QMouseEvent *event) override {
    //   //  QgsPointXY point = getCoordinateTransform()->toMapCoordinates(event->pos());
    //   //  qDebug() << "Mouse moved to:" << point.x() << point.y();
    //   QgsMapCanvas::mouseMoveEvent(event);
    // }

    // void mouseReleaseEvent(QMouseEvent *event) override {
    //     if (event->button() == Qt::LeftButton) {
    //         QgsPointXY point = getCoordinateTransform()->toMapCoordinates(event->pos());
    //         qDebug() << "Left button released at:" << point.x() << point.y();
    //     }
    //     QgsMapCanvas::mouseReleaseEvent(event);
    // }
};

#endif // MYMAPCANVAS_H
